import session from '@/utils/session'
import {
  NAVIGATION_BAR_URL
} from '@/api/config'
import irequest from '@libs/irequest'

export default {
  state: {
    category: session.get('category') || [],
    cate: session.get('cate') || []
  },
  getters: {
    category: state => state.category,
    cate: state => state.cate
  },
  actions: {
    /**
     * 设置属性列表的值
     */
    setCategoryInfo ({ state }, payload) {
      state.category = payload
      session.set('category', payload)
    },

    /**
     * 设置当前点击的属性
     */
    setCateInfo ({ state }, payload) {
      state.cate = payload
      session.set('cate', payload)
    },

    /**
     * 从接口中获取分类数据
     */
    async getCategoryInfo (state, payload) {
      // 从接口中获取数据
      // let navList = session.get('category') || []
      let navList = []
      // 如果当前获取的数据长度是0
      if (navList.length === 0) {
        // 开始请求数据
        const { data } = await irequest.request({
          url: NAVIGATION_BAR_URL,
          withLoading: true
        })
        navList = data
        console.log('navList: ', navList)
        // 给导航栏的每个导航加上left属性
        navList.forEach(nav => {
          nav.left = 0
        })
        // 将接口获取的数据保存到store中
        state.dispatch('setCategoryInfo', navList)
      }
      // 获取分类的值
      state.category = navList
      // 如果有回调，则执行回调
      payload && payload(state.category)
    }
  }
}
